<!-- 飞来汇 - 支付 -->
<template>
	<Modal
		class="fly-detail"
		class-name="vertical-center-modal" 
		width="360" 
		v-model="flyShow"
		:footer-hide="true"
		:title="$t('pay.payFlyConfirm')"
		:mask-closable="false"
		>
		<Spin size="large" fix v-if="spinShow"></Spin>
		<div class="pb-16">
			<div id="flypayContainer"></div>
		</div>
	</Modal>
</template>

<script>
	export default{
		data(){
			return{
				flyShow:false,
				spinShow:false,
			}
		},
		methods:{
			open(obj,payType){
				this.flyShow = true;
				this.initFlyPay(obj,payType);
			},
			close(){
				this.flyShow = false;
				this.spinShow = false;
			},
			loadScript(url, key){
				return new Promise((resolve, reject) => {
					if (window[key]) {
						resolve(window[key]);
						return;
					}
					const script = document.createElement('script');
					script.src = url;
					script.async = true;
					script.onload = () => resolve(window[key]);
					script.onerror = () => reject(new Error('Failed to load script'));
					document.head.appendChild(script);
				});
			},
			initFlyPay(obj,payType){
				var flypay;
				// production 正式地址 测试地址
				let url = process.env.VUE_APP_API == 'https://api.100buy.com' ? 'https://kamelnet-cdn-oss-prod.inflyway.com/front-sdk/flypay.min.js' : 'https://test.tuotuoshuke.com/third-website/flypay.min.js';
				var options = { public_key: obj.key, orderData: obj.orderData }
				options.onPaymentOrderCreated = () => {
					if(payType == 'apple'){//只显示apple支付
						flypay.render({
							APPLEPAY:'flypayContainer'
						})
					}
					if(payType == 'google'){
						flypay.render({
							GOOGLEPAY:'flypayContainer'
						})
					}
				}
				// applePay或googlePay按钮被点击时触发
				options.onClick = (res) => {
					this.spinShow = true;
				}
				// 获取到支付单提交结果时触发
				options.onSubmited = (res) => {
					this.spinShow = false;
					if(res.status == '05' || res.status == '01'){
						window.location.href = obj.orderData.return_url;
					}else if(res.status == '06'){
						window.location.href = res.redirect_url;
					}
				}
				// 提交支付单发生异常时触发。参数值为异常信息字符串
				options.onSubmitFailed = (err) => {
					this.spinShow = false;
					this.$Message.error(err);
				}
				// applePay或googlePay支付被中断
				options.onPaymentInterrupted = () => {
					this.spinShow = false;
				}
				// 创建支付单失败时，返回创建错误信息。
				options.onCreatePaymentOrderFailed = (err) => {
					this.$Message.error(err.message);
					this.spinShow = false;
					this.close();
				}
				this.loadScript(url, 'FlyPay').then((res) => { 
					flypay = new FlyPay(options);
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.fly-detail{
		#flypayContainer{
			width: 254px;
			height: 40px;
			margin: auto;
		}
	}
</style>